<?php

namespace Reusify\Helper;

class StringHelper
{
    public static function trimAll(string $string):string
    {
        $space = [' ', '　', "\t", "\n", "\r"];
        $empty = ['', '', '', '', ''];
        return str_replace($space,$empty,$string);
    }

    /**
     * 生成随机字符串
     *
     * @param int $length 随机部分长度，默认 10
     * @param string $pre 前缀，默认空
     * @return string 返回带前缀的随机字符串
     */
    public static function random(int $length = 10, string $pre = ''): string
    {
        if ($length <= 0) {
            return $pre;
        }

        // 可选字符集（大小写字母 + 数字）
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';

        // 使用随机字符生成
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }

        return $pre . $randomString;
    }

    /**
     * 将字符串按长度拆分为数组（支持多字节）
     */
    public static function chunk(string $string, int $length = 1): array
    {
        if ($length < 1) $length = 1;

        $result = [];
        $strLen = mb_strlen($string);

        for ($i = 0; $i < $strLen; $i += $length) {
            $result[] = mb_substr($string, $i, $length);
        }

        return $result;
    }

}